<template>
  <div class="goods_detail">
    <header class="top_bar">
      <a onclick="window.history.go(-1)" class="icon_back"></a>
      <h3 class="cartname">商品详情</h3>
    </header>
    <main class="detail_box">
      <section class="banner_box" style="height:350px;">
        <mt-swipe :auto="4000">
          <mt-swipe-item v-for="(item,index) in goodsImages" :key="index">
            <img :src="item" class="banner_pic">
          </mt-swipe-item>
        </mt-swipe>
      </section>
      <section class="product_info clearfix">
        <div class="product_left">
          <p class="p_name">{{goodsData.name}}</p>
          <div class="product_pric" style="color:red;font-size:20px;font-weight:bold">￥ {{priceCoin}}
          </div>
        </div>
      </section>
      <div @click="SelectFormat">
        <mt-cell :title="checkedSpecText" is-link></mt-cell>
      </div>
      <mt-popup :modal=false v-model="popupVisible" position="bottom" @click="popup" :style="popClass">
        <div class="close" @click='closeVisible'>
          <img class="ic" src="https://ailianshangquan.oss-cn-beijing.aliyuncs.com/close.png">
        </div>
        <div class="image-info">
          <img :src="prcUrl" class="goodsimg" style="width:27%;display:inline-block;">
          <div class="info">
            <div style="margin-left:20px">
              <div class="p">￥ {{priceCoin}}</div>
              <div class="messag">{{tmpSpecText}}</div>
            </div>
          </div>
        </div>
        <div class="spec-con">
          <div class="spec-item" v-for="item in specificationList" :key="item.id" style="margin-top:10px;margin-left:10px">
            <h3>{{item.name}}</h3>
            <div class="values">
              <div v-for="(vitem,indexx) in item.valueList" :key="indexx" :class="vitem.checked ? 'value selected' : 'value'" @click="clickSkuValue" style="margin-left:10px;margin-top:10px" size="small" :data-value-checkNum="checkNum" :data-value-id="vitem.id" :data-name="vitem.specification">
                {{vitem.value}}
              </div>
            </div>
          </div>
        </div>
        <div class="selectNum" style="margin-top:10px;margin-bottom:30px;margin-left:10px">
          <h3>数量</h3>
          <div style="margin-top:10px">
            <mt-button :disabled="downdisabled" class="cut" @click="down" type="default" size="small" style="width:50px;height:50px">-</mt-button>
            <input v-model="number" disabled="true" type="number" class="number">
            <mt-button :disabled="adddisabled" type="default" @click="add" size="small" style="width:50px;height:50px">+</mt-button>
          </div>
        </div>
        <mt-button size="normal" :disabled="disableds" style="width:100%;background:rgb(242,48,48);margin-bottom:10px;color: GhostWhite" @click="trueAddCart">确认</mt-button>
      </mt-popup>
      <mt-popup :modal=false v-model="Visible" position="bottom" :style="popClass">
        <div class="close" @click='closeVisible'>
          <img class="ic" src="https://ailianshangquan.oss-cn-beijing.aliyuncs.com/close.png">
        </div>
        <div class="image-info">
          <img :src="prcUrl" class="goodsimg" style="width:30%;display:inline-block;">
          <div class="info">
            <div style="margin-left:20px">
              <div class="p">￥ {{priceCoin}}</div>
              <div class="messag">{{tmpSpecText}}</div>
            </div>
          </div>
        </div>
        <div class="spec-con">
          <div class="spec-item" v-for="(item,index) in specificationList" :key="index" style="margin-top:10px;margin-left:10px">
            <h3>{{item.name}}</h3>
            <div class="values">
              <div v-for="(vitem,indexs) in item.valueList" :key="indexs" :class="vitem.checked ? 'value selected' : 'value'" @click="clickSkuValue" style="margin-left:10px;margin-top:10px" size="small" :data-value-checkNum="checkNum" :data-value-id="vitem.id" :data-name="vitem.specification">
                {{vitem.value}}
              </div>
            </div>
          </div>
        </div>
        <div class="selectNum" style="margin-top:10px;margin-bottom:30px;margin-left:10px">
          <h3>数量</h3>
          <div style="margin-top:10px">
            <mt-button :disabled="downdisabled" class="cut" @click="down" type="default" size="small" style="width:50px;height:50px">-</mt-button>
            <input v-model="number" disabled="true" type="number" class="number">
            <mt-button :disabled="adddisabled" type="default" @click="add" size="small" style="width:50px;height:50px">+</mt-button>
          </div>
        </div>
        <mt-button size="normal" :disabled="disableds" style="width:100%;background:rgb(242,48,48);margin-bottom:10px;" @click="trueAddCart">确认</mt-button>
      </mt-popup>
      <section class="product_intro">
        <p class="pro_det">
          产品参数
        </p>
      </section>
      <section>
        <div v-html="goodsData.desc" class="banner_box_img">
          {{goodsData.desc}}
        </div>
      </section>
    </main>
    <footer class="cart_d_footer" style="z-index:10001;height: 53px">
      <div class="m">
        <ul class="m_box" style="width: 40%">
          <li class="m_item">
            <div class="m_item_link Collect" style="width: 50%;margin-top:-3%" @click="setCollect">
              <div :class="collectType"></div>
              <div class="m_item_name">收藏</div>
            </div>
            <router-link :to="'/cart'" class="m_item_link" style="margin-left: 10px;width: 50%;margin-top:-3%">
              <div class="m_item_pic three" style="margin-left: 30%"></div>
              <div class="buy_number" style="margin-left: 0">
                {{cartGoodsCount}}
              </div>
              <div class="m_item_name">购物车</div>
            </router-link>
          </li>
        </ul>
        <div class="btn_box">
          <mt-button :disabled="disabled" size="small" style="width:55%;height:58px;background:rgb(244,143,24);line-height: 48px;border: 1px solid transparent;font-size: 15px;color: GhostWhite" @click="addCart">加入购物车</mt-button>
          <mt-button :disabled="disabled" size="small" @click="buynow" style="width:45%;height:58px;background:rgb(242,48,48);float:right;line-height: 48px;border: 1px solid transparent;font-size: 15px;color: GhostWhite">立即购买</mt-button>
        </div>
      </div>
    </footer>
  </div>
</template>
<script>
import { Swipe, SwipeItem, Cell, Toast, Button, MessageBox } from 'mint-ui'
export default {
  components: {
    Swipe,
    SwipeItem,
    Cell,
    Toast,
    Button
  },
  mounted() {
    this.fetchData(this.$route.params.id)
  },
  data() {
    return {
      popupVisible: false,
      cateGoodsAllData: [],
      goodsImages: [],
      goodsData: [],
      collectType: 'm_item_pic two',
      remindValue: ['', '', '赠送'],
      plusFlag: ['', '+', '  '],
      priceCoinFlag: '',
      priceCoin: 0,
      checkedSpecPriceFlag: '',
      checkedSpecPrice: 0,
      specificationList: [],
      productList: [],
      checkNum: 0,
      number: 1,
      checkedSpecText: '规格数量选择',
      soldout: false,
      tmpSpecText: '请选择规格数量',
      popClass: 'bottom:2px;width:100%;',
      disabled: false,
      addCartType: 'default',
      disableds: false,
      cartGoodsCount: 0,
      Visible: false,
      cartDatas: [],
      prcUrl: '',
      minNumber: 0,
      addNumber: 0,
      downdisabled: false,
      adddisabled: false
    }
  },
  watch: {
    $route(to) {
      var reg = /detail\/\d+/
      if (reg.test(to.path)) {
        var categotyId = this.$route.params.id || 0
        this.fetchData(categotyId)
      }
    }
  },
  methods: {
    gotoPage() {
      var _this = this
      _this.$router.push('/home')
    },
    fetchData(id) {
      var _this = this
      let uObj = {}
      if (window.sessionStorage.userInfo != null) {
        let uObj = JSON.parse(window.sessionStorage.userInfo)
        let useId = uObj.id
        _this.$http
          .get('/mechanismadmin/mobile/detail', {
            params: {
              userId: useId,
              id: id
            }
          })
          .then(
            res => {
              _this.goodsImages = res.data.data.info.gallery
              _this.goodsData = res.data.data.info
              _this.addNumber = res.data.data.info.addNumber

              _this.checkedSpecPriceFlag = res.data.data.info.integralFlag
              _this.checkedSpecPrice = res.data.data.info.integral
              _this.priceCoinFlag = res.data.data.info.priceFlag
              _this.priceCoin = res.data.data.info.retailPrice
              _this.specificationList = res.data.data.specificationList
              _this.productList = res.data.data.productList
              _this.prcUrl = res.data.data.info.picUrl
              if (_this.specificationList[0].valueList.length === 1) {
                let _specificationList = this.specificationList
                _specificationList[0].valueList[0].checked = true
                this.specifications = _specificationList
                this.checkedSpecText = _this.specificationList[0].valueList[0].value
                this.checknum()
                this.changeSpecInfo()
              }
              _this.cartGoodsCount = res.data.data.cartGoodsCount
              if (_this.cartGoodsCount > 99) {
                _this.cartGoodsCount = '99+'
              }
              if (res.data.data.userHasCollect % 2 == 1) {
                _this.collectType = 'm_item_pic twos'
              }
              var checkedProductArray = this.getCheckedProductItem(this.getCheckedSpecKey())
              var checkedProduct = checkedProductArray[0]
              if (res.data.data.info.minNumber > checkedProduct.number) {
                _this.number = checkedProduct.number
                _this.minNumber = checkedProduct.number
                console.log('ssss' + _this.minNumber)
              } else {
                _this.number = res.data.data.info.minNumber
                _this.minNumber = res.data.data.info.minNumber
                console.log('ssss' + _this.minNumber)
              }
            },
            err => {
              console.log(err)
            }
          )
      } else {
        _this.$router.push({
          path: '/login'
        })
      }
    },
    setCollect() {
      var _this = this
      //添加或是取消收藏
      let uObj = {}
      if (window.sessionStorage.userInfo != null) {
        let uObj = JSON.parse(window.sessionStorage.userInfo)
        let useId = uObj.id
        _this.$http
          .get('/mechanismadmin/mobile/addordelete', {
            params: {
              userId: useId,
              type: 0,
              valueId: this.$route.params.id || 0
            }
          })
          .then(res => {
            let _res = res
            if (_res.data.data.type == 'add') {
              _this.collectType = 'm_item_pic twos'
            } else {
              _this.collectType = 'm_item_pic two'
            }
          })
      } else {
        _this.$router.push({
          path: '/login'
        })
      }
    },
    SelectFormat() {
      this.popupVisible = true
      this.popClass = 'bottom:2px;width:100%;'
    },
    clickSkuValue(event) {
      var _this = this
      let specName = event.currentTarget.dataset.name
      let specValueId = event.currentTarget.dataset.valueId
      let _specificationList = this.specificationList
      for (let i = 0; i < _specificationList.length; i++) {
        if (_specificationList[i].name === specName) {
          for (let j = 0; j < _specificationList[i].valueList.length; j++) {
            if (_specificationList[i].valueList[j].id == specValueId) {
              //如果已经选中，则反选
              if (_specificationList[i].valueList[j].checked) {
                _specificationList[i].valueList[j].checked = false
              } else {
                _specificationList[i].valueList[j].checked = true
              }
            } else {
              _specificationList[i].valueList[j].checked = false
            }
          }
        }
      }
      _this.specificationList = _specificationList
      this.checknum()
      this.changeSpecInfo()
    },
    add() {
      var checkedProductArray = this.getCheckedProductItem(this.getCheckedSpecKey())
      var checkedProduct = checkedProductArray[0]
      if (checkedProduct.number < 0) {
        Toast({
          message: '没有库存',
          position: 'middle',
          duration: 1000
        })
      } else {
        this.number = parseInt(this.number) + this.addNumber
        if (checkedProduct.number < this.number) {
          this.number = checkedProduct.number
          this.adddisabled = true
          Toast({
            message: '库存不足',
            position: 'middle',
            duration: 1000
          })
        } else {
          this.number = this.number
        }
      }
    },
    down() {
      this.adddisabled = false
      this.number = this.number - this.addNumber > this.minNumber ? this.number - this.addNumber : this.minNumber
    },
    checknum() {
      this.checkNum = this.checkNum + 1
      if (this.number < 0) {
        this.number = 1
      }
    },
    getCheckedSpecValue() {
      let checkedValues = []
      let _specificationList = this.specificationList
      for (let i = 0; i < _specificationList.length; i++) {
        let _checkedObj = {
          name: _specificationList[i].name,
          valueId: 0,
          valueText: ''
        }
        for (let j = 0; j < _specificationList[i].valueList.length; j++) {
          if (_specificationList[i].valueList[j].checked) {
            _checkedObj.valueId = _specificationList[i].valueList[j].id
            _checkedObj.valueText = _specificationList[i].valueList[j].value
          }
        }
        checkedValues.push(_checkedObj)
      }
      return checkedValues
    },
    isCheckedAllSpec() {
      return !this.getCheckedSpecValue().some(function(v) {
        if (v.valueId == 0) {
          return true
        }
      })
    },
    getCheckedProductItem(key) {
      return this.productList.filter(function(v) {
        if (v.specifications.toString() == key.toString()) {
          return true
        } else {
          return false
        }
      })
    },
    getCheckedSpecKey() {
      let checkedValue = this.getCheckedSpecValue().map(function(v) {
        return v.valueText
      })
      return checkedValue
    },
    addCart() {
      if (this.popupVisible) {
        if (!this.soldout) {
          Toast({
            message: '请选择规格',
            position: 'middle',
            duration: 1000
          })
        } else if (this.number <= 0) {
          Toast({
            message: '商品数量不合法',
            position: 'middle',
            duration: 1000
          })
          this.number = 1
        } else if (!/^[0-9]*$/.test(this.number)) {
          Toast({
            message: '商品数量不合法',
            position: 'middle',
            duration: 1000
          })
          this.number = 1
        } else {
          let checkedProductArray = this.getCheckedProductItem(this.getCheckedSpecKey())
          let checkedProduct = checkedProductArray[0]
          if (checkedProduct != null) {
            if (checkedProduct.number < 0) {
              Toast({
                message: '没有库存',
                position: 'middle',
                duration: 1000
              })
            }
            if (this.number > checkedProduct.number) {
              Toast({
                message: '数量超出范围~',
                position: 'middle',
                duration: 1000
              })
              this.number = 1
            } else {
              //添加订单表
              let uObj = {}
              if (window.sessionStorage.userInfo != null) {
                let uObj = JSON.parse(window.sessionStorage.userInfo)
                let useId = uObj.id
                this.$http
                  .get('/mechanismadmin/mobile/adcart', {
                    params: {
                      userId: useId,
                      goodsId: this.goodsData.id,
                      productId: checkedProduct.id,
                      number: this.number
                    }
                  })
                  .then(res => {
                    if (res.data.data.message == 'success') {
                      Toast({
                        message: '成功加入购物车',
                        position: 'middle',
                        duration: 1000
                      })
                      if (this.cartGoodsCount != '99+') {
                        this.cartGoodsCount = this.cartGoodsCount + this.number
                        if (this.cartGoodsCount > 99) {
                          this.cartGoodsCount = '99+'
                        }
                      }
                    } else {
                      Toast({
                        message: '加入购物车失败，请重试',
                        position: 'middle',
                        duration: 1000
                      })
                    }
                    this.popupVisible = false
                    this.disabled = false
                  })
              } else {
                this.$router.push({
                  path: '/login'
                })
              }
            }
          }
        }
      } else {
        this.popupVisible = true
        this.popClass = 'bottom:54px;width:100%;'
        this.disabled = true
      }
    },
    changeSpecInfo() {
      let checkedNameValue = this.getCheckedSpecValue()
      let checkedValue = checkedNameValue
        .filter(function(v) {
          if (v.valueId != 0) {
            return true
          } else {
            return false
          }
        })
        .map(function(v) {
          return v.valueText
        })

      if (checkedValue.length > 0) {
        this.tmpSpecText = checkedValue.join('　')
      } else {
        this.tmpSpecText = '请选择规格数量'
      }

      if (this.isCheckedAllSpec()) {
        this.checkedSpecText = this.tmpSpecText

        // 规格所对应的货品选择以后
        let checkedProductArray = this.getCheckedProductItem(this.getCheckedSpecKey())
        if (!checkedProductArray || checkedProductArray.length <= 0) {
          this.soldout = true
          console.error('规格所对应货品不存在')
          return
        }
        let checkedProduct = checkedProductArray[0]
        if (checkedProduct.number >= 0) {
          ;(this.priceCoin = checkedProduct.price), (this.prcUrl = checkedProduct.url), console.log(this.prcUrl)
          ;(this.priceCoinFlag = checkedProduct.priceFlag),
            (this.checkedSpecPrice = checkedProduct.integral),
            (this.checkedSpecPriceFlag = checkedProduct.integralFlag),
            (this.soldout = true)
        } else {
          ;(this.checkedSpecPrice = this.goodsData.integral),
            (this.prcUrl = this.goodsData.picUrl),
            (this.checkedSpecPriceFlag = this.goodsData.integralFlag),
            (this.priceCoin = this.goodsData.price),
            (this.priceCoinFlag = this.goodsData.priceFlag),
            (this.soldout = true)
        }
      } else {
        ;(this.checkedSpecText = '规格数量选择'),
          (this.checkedSpecPrice = this.goodsData.integral),
          (this.prcUrl = this.goodsData.picUrl),
          (this.checkedSpecPriceFlag = this.goodsData.integralFlag),
          (this.priceCoin = this.goodsData.retailPrice),
          (this.priceCoinFlag = this.goodsData.priceFlag),
          (this.soldout = false)
      }
    },
    trueAddCart() {
      if (!this.soldout) {
        Toast({
          message: '请选择规格',
          position: 'middle',
          duration: 1000,
          className: 'toastFormat'
        })
      } else if (this.number <= 0) {
        Toast({
          message: '商品数量不合法',
          position: 'middle',
          duration: 1000
        })
        this.number = 1
      } else if (!/^[0-9]*$/.test(this.number)) {
        Toast({
          message: '商品数量不合法',
          position: 'middle',
          duration: 1000
        })
        this.number = 1
      } else {
        let checkedProductArray = this.getCheckedProductItem(this.getCheckedSpecKey())
        let checkedProduct = checkedProductArray[0]
        if (checkedProduct != null) {
          if (checkedProduct.number <= 0) {
            Toast({
              message: '没有库存',
              position: 'middle',
              duration: 1000
            })
          }
          if (this.number > checkedProduct.number) {
            Toast({
              message: '数量超出范围~',
              position: 'middle',
              duration: 1000
            })
            this.number = 1
          } else {
            //添加订单表
            let uObj = {}
            if (window.sessionStorage.userInfo != null) {
              let uObj = JSON.parse(window.sessionStorage.userInfo)
              let useId = uObj.id
              this.disableds = true
              this.disabled = true
              if (this.popupVisible) {
                this.$http
                  .get('/mechanismadmin/mobile/adcart', {
                    params: {
                      userId: useId,
                      goodsId: this.goodsData.id,
                      productId: checkedProduct.id,
                      number: this.number
                    }
                  })
                  .then(res => {
                    if (res.data.data.message == 'success') {
                      Toast({
                        message: '成功加入购物车',
                        position: 'middle',
                        duration: 1000
                      })
                      this.cartGoodsCount = this.cartGoodsCount + this.number
                    } else {
                      Toast({
                        message: '加入购物车失败，请重试',
                        position: 'middle',
                        duration: 1000
                      })
                    }
                    this.popupVisible = false
                    this.disabled = false
                    this.disableds = false
                  })
              } else {
                this.$http
                  .get('/mechanismadmin/mobile/buynow', {
                    params: {
                      userId: useId,
                      goodsId: this.goodsData.id,
                      productId: checkedProduct.id,
                      number: this.number
                    }
                  })
                  .then(res => {
                    this.cartDatas = res.data.data.cart
                    this.checkThis()
                    window.sessionStorage.cartDatas = JSON.stringify(this.cartDatas)
                    window.sessionStorage.totalMoney = JSON.stringify(this.number * this.priceCoin)
                    this.$router.push('/pay')
                  })
              }
            } else {
              this.$router.push({
                path: '/login'
              })
            }
          }
        }
      }
    },
    popup() {},
    buynow() {
      if (this.popupVisible) {
        if (!this.soldout) {
          Toast({
            message: '请选择规格',
            position: 'middle',
            duration: 1000
          })
        } else if (this.number <= 0) {
          Toast({
            message: '商品数量不合法',
            position: 'middle',
            duration: 1000
          })
          this.number = 1
        } else if (!/^[0-9]*$/.test(this.number)) {
          Toast({
            message: '商品数量不合法',
            position: 'middle',
            duration: 1000
          })
          this.number = 1
        } else {
          let checkedProductArray = this.getCheckedProductItem(this.getCheckedSpecKey())
          let checkedProduct = checkedProductArray[0]
          if (checkedProduct != null) {
            if (checkedProduct.number < 0) {
              Toast({
                message: '没有库存',
                position: 'middle',
                duration: 1000
              })
            }
            if (this.number > checkedProduct.number) {
              Toast({
                message: '数量超出范围~',
                position: 'middle',
                duration: 1000
              })
              this.number = 1
            } else {
              //添加订单表
              let uObj = {}
              if (window.sessionStorage.userInfo != null) {
                let uObj = JSON.parse(window.sessionStorage.userInfo)
                let useId = uObj.id
                this.$http
                  .get('/mechanismadmin/mobile/buynow', {
                    params: {
                      userId: useId,
                      goodsId: this.goodsData.id,
                      productId: checkedProduct.id,
                      number: this.number
                    }
                  })
                  .then(res => {
                    this.cartDatas = res.data.data.cart
                    this.checkThis()
                    window.sessionStorage.cartDatas = JSON.stringify(this.cartDatas)
                    window.sessionStorage.totalMoney = JSON.stringify(this.number * this.priceCoin)
                    this.$router.push('/pay')
                  })
              } else {
                this.$router.push({
                  path: '/login'
                })
              }
            }
          }
        }
      } else {
        this.Visible = true
        this.popClass = 'bottom:54px;width:100%;'
        this.disabled = true
      }
    },
    closeVisible() {
      this.Visible = false
      this.popupVisible = false
      this.disabled = false
    },
    checkThis() {
      this.cartDatas = this.cartDatas.map(function(v) {
        if (v.checked) {
          v.checked = false
        } else {
          v.checked = true
        }
        return v
      })
    }
  }
}
</script>
<style>
@import '../assets/css/detail.css';
</style>



